/**
 * 认证服务层
 */
const userDao = require('../dao/userDao');
const { generateToken, generateRefreshToken, verifyRefreshToken } = require('../utils/auth');
const { 
  validateRequired, 
  validateEmail, 
  validatePhone, 
  validatePassword, 
  validateUsername 
} = require('../utils/validation');

/**
 * 用户登录服务
 * @param {Object} loginData - 登录数据 {username, password}
 * @returns {Object} 登录结果
 */
const loginUser = async (loginData) => {
  const { username, password } = loginData;

  // 参数验证
  const validation = validateRequired(loginData, ['username', 'password']);
  if (!validation.isValid) {
    throw new Error(validation.message);
  }

  // 查找用户
  const user = await userDao.findUserByUsername(username);
  if (!user) {
    throw new Error('用户名或密码错误');
  }

  // 验证密码（前端已加密，直接比较字符串）
  if (password !== user.password) {
    throw new Error('用户名或密码错误');
  }

  // 检查用户状态
  if (user.status !== 'active') {
    throw new Error('账号已被禁用，请联系管理员');
  }

  // 生成令牌
  const tokenPayload = {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    role: user.role || 'user'
  };
  const token = generateToken(tokenPayload);
  const refreshToken = generateRefreshToken(tokenPayload);

  // 更新最后登录时间
  await userDao.updateUser(user.id, {
    last_login_at: new Date()
  });

  return {
    token,
    refreshToken,
    expiresIn: 7200, // 2小时
    userInfo: {
      id: user.id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      phone: user.phone,
      email: user.email,
      level: user.level,
      experience: user.experience
    }
  };
};

/**
 * 用户注册服务
 * @param {Object} registerData - 注册数据
 * @returns {Object} 注册结果
 */
const registerUser = async (registerData) => {
  const { username, password, nickname, phone, verifyCode } = registerData;

  // 参数验证
  const validation = validateRequired(registerData, ['username', 'password', 'nickname', 'phone']);
  if (!validation.isValid) {
    throw new Error(validation.message);
  }

  // 验证用户名格式
  const usernameValidation = validateUsername(username);
  if (!usernameValidation.isValid) {
    throw new Error(usernameValidation.message);
  }

  // 验证密码强度
  const passwordValidation = validatePassword(password);
  if (!passwordValidation.isValid) {
    throw new Error(passwordValidation.message);
  }

  // 验证手机号格式
  if (!validatePhone(phone)) {
    throw new Error('手机号格式不正确');
  }

  // TODO: 验证短信验证码
  // if (!verifyCode || verifyCode !== '123456') {
  //   throw new Error('验证码错误');
  // }

  // 检查用户名是否已存在
  const existingUser = await userDao.findUserByUsername(username);
  if (existingUser) {
    throw new Error('用户名已存在');
  }

  // 检查手机号是否已存在
  const existingPhone = await userDao.findUserByPhone(phone);
  if (existingPhone) {
    throw new Error('手机号已被注册');
  }

  // 创建用户（前端已加密密码，直接存储）
  const userData = {
    username,
    password, // 前端已加密，直接使用
    nickname,
    phone,
    status: 'active',
    level: 1,
    experience: 0,
    total_study_time: 0,
    practice_count: 0
  };

  const newUser = await userDao.createUser(userData);

  // 生成令牌
  const tokenPayload = {
    id: newUser.id,
    username: newUser.username,
    nickname: newUser.nickname,
    role: newUser.role || 'user'
  };
  const token = generateToken(tokenPayload);
  const refreshToken = generateRefreshToken(tokenPayload);

  return {
    token,
    refreshToken,
    expiresIn: 7200,
    userInfo: {
      id: newUser.id,
      username: newUser.username,
      nickname: newUser.nickname,
      avatar: newUser.avatar,
      phone: newUser.phone,
      email: newUser.email,
      level: newUser.level,
      experience: newUser.experience
    }
  };
};

/**
 * 刷新令牌服务
 * @param {string} refreshToken - 刷新令牌
 * @returns {Object} 新的令牌信息
 */
const refreshTokenService = async (refreshToken) => {
  if (!refreshToken) {
    throw new Error('缺少刷新令牌');
  }

  try {
    // 验证刷新令牌
    const decoded = verifyRefreshToken(refreshToken);
    
    // 获取用户信息
    const user = await userDao.findById(decoded.id);
    if (!user) {
      throw new Error('用户不存在');
    }

    if (user.status !== 'active') {
      throw new Error('账号已被禁用');
    }

    // 生成新的访问令牌
    const tokenPayload = {
      id: user.id,
      username: user.username,
      nickname: user.nickname,
      role: user.role || 'user'
    };
    const newToken = generateToken(tokenPayload);
    const newRefreshToken = generateRefreshToken(tokenPayload);

    return {
      token: newToken,
      refreshToken: newRefreshToken,
      expiresIn: 7200
    };
  } catch (error) {
    throw new Error('刷新令牌无效或已过期');
  }
};

/**
 * 获取用户信息服务
 * @param {number} userId - 用户ID
 * @returns {Object} 用户信息
 */
const getUserProfile = async (userId) => {
  const user = await userDao.findById(userId);
  if (!user) {
    throw new Error('用户不存在');
  }

  return {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    avatar: user.avatar,
    phone: user.phone,
    email: user.email,
    level: user.level,
    experience: user.experience,
    total_study_time: user.total_study_time,
    practice_count: user.practice_count,
    created_at: user.created_at
  };
};

/**
 * 更新用户信息服务
 * @param {number} userId - 用户ID
 * @param {Object} updateData - 更新数据
 * @returns {Object} 更新后的用户信息
 */
const updateUserProfile = async (userId, updateData) => {
  const { nickname, email, avatar } = updateData;

  // 验证邮箱格式
  if (email && !validateEmail(email)) {
    throw new Error('邮箱格式不正确');
  }

  // 检查邮箱是否已被其他用户使用
  if (email) {
    const existingUser = await userDao.findUserByEmail(email);
    if (existingUser && existingUser.id !== userId) {
      throw new Error('邮箱已被其他用户使用');
    }
  }

  const updateFields = {};
  if (nickname) updateFields.nickname = nickname;
  if (email) updateFields.email = email;
  if (avatar) updateFields.avatar = avatar;

  await userDao.updateUser(userId, updateFields);
  
  return await getUserProfile(userId);
};

/**
 * 修改密码服务
 * @param {number} userId - 用户ID
 * @param {Object} passwordData - 密码数据
 * @returns {boolean} 修改结果
 */
const changePassword = async (userId, passwordData) => {
  const { oldPassword, newPassword } = passwordData;

  // 参数验证
  const validation = validateRequired(passwordData, ['oldPassword', 'newPassword']);
  if (!validation.isValid) {
    throw new Error(validation.message);
  }

  // 验证新密码强度
  const passwordValidation = validatePassword(newPassword);
  if (!passwordValidation.isValid) {
    throw new Error(passwordValidation.message);
  }

  // 获取用户信息
  const user = await userDao.findById(userId);
  if (!user) {
    throw new Error('用户不存在');
  }

  // 验证旧密码（前端已加密，直接比较字符串）
  if (oldPassword !== user.password) {
    throw new Error('原密码错误');
  }

  // 更新密码（前端已加密，直接存储）
  await userDao.updateUser(userId, {
    password: newPassword
  });

  return true;
};

module.exports = {
  loginUser,
  registerUser,
  refreshTokenService,
  getUserProfile,
  updateUserProfile,
  changePassword
};
